package com.zoe.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

public class GenerateSvnFileService {

	public void generateSvnFile(GenerateSvnModel generateSvnModel){
		
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(generateSvnModel.getSvnPath()));
			String string = null;

			while ((string = reader.readLine()) != null) {
				String filename = string.substring(string.lastIndexOf('/') + 1);
				if (filename.contains(".")) {
					String sourceFile = generateSvnModel.getProjectPath() + string.substring(string.indexOf("/"));
					String destFile = generateSvnModel.getDestPath() + string.substring(string.indexOf("/"));
					copyFile(new File(sourceFile), new File(destFile));
				}
				if (filename.endsWith(".java")) // 编译之后生成class文件，且要考虑内部类的情况
				{
					final String temp = filename.substring(0, filename.indexOf(".java")); // 去掉扩展名之后的文件名
					String classDir = generateSvnModel.getClassPath() + string.substring(string.indexOf("/com"), string.lastIndexOf('/'));
					final String destDir = generateSvnModel.getDestPath() + "/WEB-INF/classes" + string.substring(string.indexOf("/com"), string.lastIndexOf('/'));

					new File(classDir).listFiles(new FileFilter() {
						public boolean accept(File file) {
							if (file.getName().equals(temp + ".class") || file.getName().startsWith(temp + "$")) {
								String dest = destDir + "/" + file.getName();
								copyFile(file, new File(dest));
								return true;
							}
							return false;
						}
					});
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 拷贝文件
	 * 
	 * @param source
	 *            原文件
	 * @param dest
	 *            目标文件
	 */
	public static void copyFile(File source, File dest) {
		FileInputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
			if (!dest.exists()) {
				dest.getParentFile().mkdirs();
			}
			inputStream = new FileInputStream(source);
			outputStream = new FileOutputStream(dest);
			byte[] bs = new byte[8192];
			int size = 0;
			while ((size = inputStream.read(bs)) != -1) {
				outputStream.write(bs, 0, size);
			}
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (outputStream != null)
					outputStream.close();
				if (inputStream != null)
					inputStream.close();
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
	}
}
